import { HttpClient } from '@angular/common/http';
import { NONE_TYPE } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router'
import axios from 'axios';

@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.css']
})
export class RoomComponent implements OnInit {

  rooms =[];
  user;
  private timer

  constructor(private http: HttpClient,private route: ActivatedRoute, private router: Router) {
    this.getCurrentUser();

    this.timer = setInterval(() => {
      this.getRoom();
    }, 1000);

   }

  ngOnInit(): void {
  }


  getRoom() {
    let baseUrl = "http://localhost:8999";

    axios.get(baseUrl+'/room/getAllRooms').then(res=>{
      this.rooms = res.data;
      //console.log(res.data)
      }).catch((err)=>{
        console.log(err);
     }).finally(()=>{
        console.log('执行完了');
     });

    // return true;
}

  public createRoom(obj){
    //console.log(obj.value.question)

    var params = new URLSearchParams()
    params.append('roomName', obj.value.roomName)
    params.append('userId', this.user.userId)
    this.getData(params, "/room/createRoom" );

  }

  public getCurrentUser(){
    let baseUrl = "http://localhost:8999";

     axios.get(baseUrl+'/user/getCurrentUser', {withCredentials: true}).then(res=>{

      this.user = res.data;
      if(!this.user){
       this.router.navigate(['/login']);
      }
      console.log(res)
      //this.isDataLoaded =true
      }).catch((err)=>{
        console.log(err);
     }).finally(()=>{
        console.log('执行完了');
     });
  }

  public async getData(params:URLSearchParams, url:String){
    let baseUrl = "http://localhost:8999";
    await  axios.post(baseUrl+url, params)
    .then(function (response) {
      //console.log(response);
      return response;
    })
    .catch(function (error) {
      //console.log(error);
    });
    }

  //销毁组件时清除定时器
  ngOnDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

}
